package chapter08

/**
 *
 * @author cdhuangchao3
 * @date 2023/6/11 3:58 PM
 */
object Test02_MatchTypes {
  def main(args: Array[String]): Unit = {
    // 1.匹配常量
    def describeConst(x: Any): String = x match {
      case 1 => "Int one"
      case "hello" => "String hello"
      case true => "Boolean true"
      case '+' => "Char +"
      case _ => ""
    }

    println(describeConst(1))
    println(describeConst("hello"))
    println(describeConst(true))
    println(describeConst(false))
    println("=" * 20)

    // 2.匹配类型
    def describeType(x: Any): String = x match {
      case i: Int => s"Int ${i}"
      case s: String => s"String ${s}"
      case list: List[String] => s"List ${list}"
      case array: Array[Int] => s"Array[Int] ${array.mkString(",")}"
      case a => s"Something else: ${a}"
    }

    println(describeType(3))
    println(describeType("a"))
    println(describeType(List[String]()))
    println(describeType(List(1, 3)))
    println(describeType(Array(1, 3)))
    println(describeType(Array('a', 'b')))

    println("=" * 20)
    // 3.匹配数组
    for (arr <- List(
      Array(0),
      Array(1, 0),
      Array(0, 1, 0),
      Array(1, 1, 0),
      Array(2, 3, 7, 15),
      Array("hello", 20, 30)
    )) {
      val result = arr match {
        case Array(0) => "0"
        case Array(1, 0) => "Array(1,0)"
        case Array(x, y) => s"Array: ${x} ${y}"
        case Array(0, _*) => "以0开头的数组"
        case Array(x, 1, z) => "中间为1的三元素数组"
        case _ => "something else"
      }
      println(result)
    }

    println("=" * 20)
    // 4.匹配列表
    for (list <- List(
      List(0),
      List(1, 0),
      List(0, 0, 0),
      List(1, 1, 0),
      List(88),
    )) {
      println(list match {
        case List(0) => "0"
        case List(x, y) => s"List(x,y): ${x} ${y}"
        case List(0, _*) => "List(0, ....)"
        case List(a) => s"List(a) ${a}"
        case _ => "something else"
      })
    }

    println("=" * 20)
    // 方式二
    val list = List(1, 2, 5, 7, 24)
    list match {
      case first :: second2 :: rest => println(s"first: ${first} second:${second2}, rest:${rest}")
      case _ => println("something else")
    }

    println("=" * 20)
    // 5.匹配元组
    for (tuple <- List(
      (0, 1),
      (0, 0),
      (0, 1, 0),
      (0, 1, 1),
      (1, 23, 56),
      ("hello", true, 0.5)
    )) println(tuple match {
      case (a, b) => s"${a}, ${b}"
      case (0, _) => "(0, _)"
      case (a, 1, _) => s"(a,1,_) ${a}"
      case (x,y,z) => s"(x,y,z) ${x} ${y} ${z}"
      case _ => println("something else")
    })
  }
}
